<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="85px">
          <el-form-item label="数据源名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入数据源名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="数据源表名" prop="tableName">
            <el-input v-model="queryParams.tableName" placeholder="请输入数据源表名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择是否启用" clearable>
              <el-option
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:dataSource:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:dataSource:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:dataSource:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:dataSource:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="dataSourceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="dataSourceId" v-if="true" />
        <el-table-column label="数据源名称" align="center" prop="name" />
        <el-table-column label="数据源表名称" align="center" prop="tableName" />
        <el-table-column label="数据源表ID" align="center" prop="tableId" />
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="映射字段" align="center" prop="crossField" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="创建人" align="center" prop="createByName" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updateByName" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dataSource:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleSource(scope.row)" ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:dataSource:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改数据源维护对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dataSourceFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="数据源名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="数据源表名称" prop="tableName">
          <el-input v-model="form.tableName" placeholder="请输入数据源表名称" />
        </el-form-item>
        <el-form-item label="数据源表ID" prop="tableId">
          <el-input v-model="form.tableId" placeholder="请输入数据源表ID" />
        </el-form-item>
        <el-form-item label="父级字段" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入父级字段" />
        </el-form-item>
        <el-form-item label="路径字段" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径字段（树状结构使用）" />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="映射字段" prop="crossField">
          <el-input v-model="form.crossField" placeholder="请输入映射字段" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据源映射列表 -->
    <el-dialog :title="dialog.title" v-model="dialog.sourceDataVisible" width="800px" append-to-body>
      <div class="search" v-show="showSearch">
        <el-form :model="sourceDataQuery" ref="sourceDataQueryFormRef" :inline="true" label-width="85px">
          <el-form-item label="映射值" prop="crossFieldValue">
            <el-input v-model="sourceDataQuery.crossFieldValue" placeholder="请输入数据源映射值" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleDataSourceQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetDataSourceQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-card shadow="never">
        <el-table v-loading="sourceDataLoading" :data="sourceDataList" height="450">
          <el-table-column label="数据源ID" align="center" prop="tableId" />
          <el-table-column label="映射值" align="center" prop="crossFieldValue" />
        </el-table>
      </el-card>

      <pagination
        v-show="sourceDataTotal>0"
        :total="sourceDataTotal"
        v-model:page="sourceDataQuery.pageNum"
        v-model:limit="sourceDataQuery.pageSize"
        @pagination="getDataList"
      />
    </el-dialog>
  </div>
</template>

<script setup name="DataSource" lang="ts">
import {
  listDataSource,
  getDataSource,
  delDataSource,
  addDataSource,
  updateDataSource,
  checkTableName,
  checkTableField,
  getSourceDataList
} from '@/api/sheet/dataSource';
import {
  DataSourceVO,
  DataSourceQuery,
  DataSourceForm,
  DataSourceDtoQuery,
  DataSourceDto
} from '@/api/sheet/dataSource/types';
import { ComponentInternalInstance } from 'vue';
import { ElForm } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));

const dataSourceList = ref<DataSourceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref(ElForm);
const dataSourceFormRef = ref(ElForm);

const dialog = reactive<DataSourceDialogOption>({
  visible: false,
  title: '',
  sourceDataVisible: false,
});

const initFormData: DataSourceForm = {
  dataSourceId: undefined,
  name: undefined,
  tableName: undefined,
  tableId: undefined,
  parentId: undefined,
  status: 'Y',
  crossField: undefined,
  remark: undefined,
}

/**
 * 校验数据源表名
 * @param rule
 * @param value
 * @param callback
 */
const validateTableName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('数据源表名称不能为空'))
  } else {
    if (form.value.tableName !== '') {
      checkTableName(form.value.tableName).then(res =>{
        if (res.data == 0){
          callback(new Error('未查询到该数据源表名'))
        } else {
          callback()
        }
      });
    } else {
      callback()
    }
  }
}

/**
 * 表字段校验
 * @param rule
 * @param value
 * @param callback
 */
const validateTableId = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('数据源表ID不能为空'))
  } else {
    if (form.value.tableName == '' || form.value.tableName == undefined) {
        callback(new Error('请先输入数据源表名'))
    } else {
      setTimeout(() => {
        checkTableField(form.value.tableName, value).then(res =>{
          if (res.data == 0){
            callback(new Error('该数据源表名中没有此字段'))
          } else {
            callback()
          }
        });
      }, 600)
    }
  }
}

const data = reactive<PageData<DataSourceForm, DataSourceQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    tableName: undefined,
    status: undefined,
  },
  rules: {
    name: [
      { required: true, message: "数据源名称不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
    ],
    tableName: [
      { required: true, message: "数据源表名称不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
      { validator: validateTableName, trigger: 'blur' }
    ],
    tableId: [
      { required: true, message: "数据源表ID不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
      { validator: validateTableId, trigger: 'blur' }
    ],
    crossField: [
      { required: true, message: "映射字段不能为空", trigger: "blur" },
      { max: 50, message: '长度不能超过50个字符', trigger: 'blur' },
      { validator: validateTableId, trigger: 'blur' }
    ],
    remark: [
      { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/**
 * 数据源映射查询
 */
const sourceDataQuery = reactive<DataSourceDtoQuery>(
  {
    pageNum: 1,
    pageSize: 10,
    dataSourceId: undefined,
    crossFieldValue: undefined,
  }
);
/** 数据源映射列表 */
const sourceDataList = ref<DataSourceDto[]>([]);
const sourceDataTotal = ref(0);
const sourceDataLoading = ref(true);
const sourceDataQueryFormRef = ref(ElForm);

/** 查询数据源维护列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDataSource(queryParams.value);
  dataSourceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  dataSourceFormRef.value.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DataSourceVO[]) => {
  ids.value = selection.map(item => item.dataSourceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = "添加数据源维护";
  nextTick(() => {
    reset();
  });
}

/** 修改按钮操作 */
const handleUpdate = (row?: DataSourceVO) => {
  loading.value = true
  dialog.visible = true;
  dialog.title = "修改数据源维护";
  nextTick(async () => {
    reset();
    const _dataSourceId = row?.dataSourceId || ids.value[0]
    const res = await getDataSource(_dataSourceId);
    loading.value = false;
    Object.assign(form.value, res.data);
  });
}

/** 提交按钮 */
const submitForm = () => {
  dataSourceFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.dataSourceId) {
        await updateDataSource(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addDataSource(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DataSourceVO) => {
  const _dataSourceIds = row?.dataSourceId || ids.value;
  await proxy?.$modal.confirm('是否确认删除数据源维护编号为"' + _dataSourceIds + '"的数据项？').finally(() => loading.value = false);
  await delDataSource(_dataSourceIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/dataSource/export', {
    ...queryParams.value
  }, `dataSource_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});

/** 打开数据源映射列表 */
const handleSource = async (row?: DataSourceVO) => {
  dialog.title = "数据源映射列表";
  dialog.sourceDataVisible = true;
  sourceDataQuery.dataSourceId = row?.dataSourceId;
  await getDataList();
}

/** 查看数据源映射列表 */
const getDataList = async () => {
  sourceDataLoading.value = true;
  const res = await getSourceDataList(sourceDataQuery);
  sourceDataList.value = res.rows;
  sourceDataTotal.value = res.total;
  sourceDataLoading.value = false;
}

/** 数据源映射列表查询按钮操作 */
const handleDataSourceQuery = () => {
  sourceDataQuery.pageNum = 1;
  getDataList();
}

/** 数据源映射列表重置按钮操作 */
const resetDataSourceQuery = () => {
  sourceDataQueryFormRef.value.resetFields();
  handleDataSourceQuery();
}
</script>
